package com.itao.snmp;

import org.snmp4j.*;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.MPv3;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.security.SecurityModels;
import org.snmp4j.security.SecurityProtocols;
import org.snmp4j.security.USM;
import org.snmp4j.smi.*;
import org.snmp4j.transport.DefaultUdpTransportMapping;

import java.io.IOException;

public class SnmpClient {

    public static void main(String[] args) {
        Snmp snmp = null;
        try {
            // 创建SNMP对象
            TransportMapping<?> transport = new DefaultUdpTransportMapping();
            snmp = new Snmp(transport);
            transport.listen();

            // 设置目标地址
            USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(MPv3.createLocalEngineID()), 0);
            SecurityModels.getInstance().addSecurityModel(usm);
            Address targetAddress = GenericAddress.parse("udp:172.16.4.61/30000");
            CommunityTarget target = new CommunityTarget();
            target.setCommunity(new OctetString("public"));
            target.setAddress(targetAddress);
            target.setRetries(2);
            target.setTimeout(1500);
            target.setVersion(SnmpConstants.version2c);

            // 设置要查询的OID
            PDU pdu = new PDU();
            pdu.add(new VariableBinding(new OID("1.3.6.1.2.1.2.2.1.16"))); // 系统描述符
            pdu.setType(PDU.GET);

            // 发送请求并获取响应
            ResponseEvent responseEvent = snmp.send(pdu, target);
            if (responseEvent != null) {
                PDU response = responseEvent.getResponse();
                if (response != null) {
                    for (int i = 0; i < response.size(); i++) {
                        VariableBinding vb = response.get(i);
                        System.out.println(vb.getOid() + " = " + vb.getVariable());
                    }
                } else {
                    System.out.println("Error: Response PDU is null");
                }
            } else {
                System.out.println("Error: ResponseEvent is null");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (snmp != null) {
                try {
                    snmp.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
